package com.daka.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service("redisClient")
public class RedisClient {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private final static Logger LOGGER = LoggerFactory.getLogger(RedisClient.class);

    public Object get(String key1, String key2, Class<?> cls) {
        if (key1 == null || key2 == null) {
            return null;
        }
        Object orderString = null;
        try {
            orderString = redisTemplate.opsForHash().get(key1, key2);
        } catch (Exception e) {
            LOGGER.info("redis get error:" + key1 + "orderCode:" + key2);
        }
        if (orderString == null) {
            return null;
        }
        return JSONObject.parseObject(orderString.toString(), cls);
    }

    public void set(String key1, String key2, Object obj) {
        try {
            String json = JSONObject.toJSONString(obj);
            redisTemplate.opsForHash().put(key1, key2, json);
            LOGGER.info("redis set key store:" + key1 + "orderCode:" + key2);
        } catch (Exception e) {
            LOGGER.info("redis set error:" + key1 + "orderCode:" + key2);
        }
    }

    public void remove(String key1, String key2) {
        try {
            redisTemplate.opsForHash().delete(key1, key2);
        } catch (Exception e) {
            LOGGER.info("redis remove error:" + key1 + "orderCode:" + key2);
        }
    }

    public Boolean expire(String key, int seconds) {
        return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }
}
